<template>
  <div class="dashboard-container">
    <!-- 页面标题和更新时间 -->
    <div class="dashboard-header">
      <div class="header-content">
        <h1 class="page-title">系统首页</h1>
        <div class="update-time">
          <el-icon><Clock /></el-icon>
          <span>更新时间：{{ updateTime }}</span>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片区域 -->
    <div class="stats-cards">
      <div class="card-row">
        <!-- 访客数卡片 -->
        <el-card class="stat-card visitor-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">访客数</div>
              <div class="card-value">{{ formatNumber(statsData.visitors) }}</div>
              <div class="card-trend up">
                <el-icon><TrendCharts /></el-icon>
                <span>{{ statsData.visitorTrend }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 付费用户数卡片 -->
        <el-card class="stat-card paid-user-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">付费用户数</div>
              <div class="card-value">{{ formatNumber(statsData.paidUsers) }}</div>
              <div class="card-trend up">
                <el-icon><TrendCharts /></el-icon>
                <span>{{ statsData.paidUserTrend }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 浏览量卡片 -->
        <el-card class="stat-card pageview-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">浏览量</div>
              <div class="card-value">{{ formatNumber(statsData.pageviews) }}</div>
              <div class="card-trend up">
                <el-icon><ArrowUp /></el-icon>
                <span>{{ statsData.pageviewTrend }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 支付订单数卡片 -->
        <el-card class="stat-card order-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">支付订单数</div>
              <div class="card-value">{{ formatNumber(statsData.orders) }}</div>
              <div class="card-trend up">
                <el-icon><ArrowUp /></el-icon>
                <span>{{ statsData.orderTrend }}%</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 支付金额卡片 -->
        <el-card class="stat-card payment-card" shadow="hover">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">支付金额</div>
              <div class="payment-details">
                <div class="payment-item">
                  <span class="payment-label">今日</span>
                  <span class="payment-value">¥{{ formatNumber(statsData.todayPayment) }}</span>
                </div>
                <div class="payment-item">
                  <span class="payment-label">昨日</span>
                  <span class="payment-value">¥{{ formatNumber(statsData.yesterdayPayment) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <span class="chart-title">支付金额对比</span>
            <div class="chart-legend">
              <div class="legend-item">
                <div class="legend-color today"></div>
                <span>今日</span>
              </div>
              <div class="legend-item">
                <div class="legend-color yesterday"></div>
                <span>昨日</span>
              </div>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <v-chart 
            class="chart" 
            :option="chartOption" 
            autoresize
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { 
  Clock, 
  User, 
  Avatar, 
  View, 
  ShoppingCart, 
  Money, 
  TrendCharts 
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { dashboardApi, mockDashboardApi } from '@/api/dashboard'
import { ElMessage } from 'element-plus'

// 注册ECharts组件
use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const updateTime = ref(dayjs().format('YYYY/MM/DD HH:mm'))

// 统计数据
const statsData = reactive({
  visitors: 126560,
  visitorTrend: 12,
  paidUsers: 26560,
  paidUserTrend: 6,
  pageviews: 465600,
  pageviewTrend: 5,
  orders: 5600,
  orderTrend: 8,
  todayPayment: 610000,
  yesterdayPayment: 549000
})

// 图表配置
const chartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: function(params) {
      const data = params[0]
      return `${data.name}<br/>${data.seriesName}: ¥${formatNumber(data.value)}`
    }
  },
  legend: {
    data: ['今日支付金额', '昨日支付金额'],
    top: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['支付金额对比'],
    axisLine: {
      lineStyle: {
        color: '#e0e0e0'
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#666'
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#666',
      formatter: function(value) {
        return '¥' + (value / 1000) + 'K'
      }
    },
    splitLine: {
      lineStyle: {
        color: '#f0f0f0'
      }
    }
  },
  series: [
    {
      name: '今日支付金额',
      type: 'bar',
      data: [statsData.todayPayment],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: '#4facfe'
            },
            {
              offset: 1,
              color: '#00f2fe'
            }
          ]
        },
        borderRadius: [4, 4, 0, 0]
      },
      barWidth: '40%'
    },
    {
      name: '昨日支付金额',
      type: 'bar',
      data: [statsData.yesterdayPayment],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: '#fa709a'
            },
            {
              offset: 1,
              color: '#fee140'
            }
          ]
        },
        borderRadius: [4, 4, 0, 0]
      },
      barWidth: '40%'
    }
  ]
})

// 格式化数字，添加千分位分隔符
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 更新时间的定时器
let timeInterval = null

// 加载数据
const loadDashboardData = async () => {
  try {
    // 尝试从真实API获取数据，如果失败则使用模拟数据
    let response
    try {
      response = await dashboardApi.getDashboardStats()
    } catch (error) {
      console.warn('真实API不可用，使用模拟数据:', error)
      response = await mockDashboardApi.getDashboardStats()
    }
    
    if (response.code === 200) {
      Object.assign(statsData, response.data)
      // 更新图表数据
      chartOption.value.series[0].data = [statsData.todayPayment]
      chartOption.value.series[1].data = [statsData.yesterdayPayment]
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

onMounted(() => {
  // 每分钟更新时间
  timeInterval = setInterval(() => {
    updateTime.value = dayjs().format('YYYY/MM/DD HH:mm')
  }, 60000)
  
  // 加载数据
  loadDashboardData()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.dashboard-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
  border-radius: 12px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0;
}

.update-time {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  opacity: 0.9;
}

.stats-cards {
  margin-bottom: 24px;
}

.card-row {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.card-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0.1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 访客数卡片 */
.visitor-card .card-content::before {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 付费用户数卡片 */
.paid-user-card .card-content::before {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

/* 浏览量卡片 */
.pageview-card .card-content::before {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

/* 订单数卡片 */
.order-card .card-content::before {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

/* 支付金额卡片 */
.payment-card .card-content::before {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.card-icon {
  font-size: 32px;
  color: white;
  margin-right: 16px;
  position: relative;
  z-index: 1;
}

.card-info {
  flex: 1;
  position: relative;
  z-index: 1;
}

.card-title {
  color: white;
  font-size: 14px;
  margin-bottom: 8px;
  opacity: 0.9;
}

.card-value {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.card-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.card-trend.up {
  color: #52c41a;
}

.card-trend.down {
  color: #ff4d4f;
}

.payment-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payment-label {
  color: white;
  font-size: 12px;
  opacity: 0.8;
}

.payment-value {
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.chart-section {
  margin-top: 24px;
}

.chart-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.chart-legend {
  display: flex;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-color.today {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.legend-color.yesterday {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart {
  height: 100%;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .card-row {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .card-row {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .header-content {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .card-row {
    grid-template-columns: 1fr;
  }
  
  .dashboard-container {
    padding: 16px;
  }
}
</style>
